//
//  ParserRIG.java
//  TopoManipApplet
//
//  Created by Thibaud PIQUET on 26/03/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

package src.convertisseur;
import java.util.*;
import java.io.*;
import org.jdom.*;

/**
 *
 * @author Thibaud PIQUET
 * 
 * Version 1.1 - Ksoobrayen : Evolutions vers un fichier graphML --> Le 05 mars 2011
 */
public class ParserRIG implements Runnable{
	
    File ftp; // File to parse
	File fileOut; // File to create
    Reader fr; // File Reader
    BufferedReader br; // Buffer Reader
    String line;
    String chaine;
    String[] res;

    String[] keyGraphNode = {"AS","location","status","switch", "name"};
    String[] keyGraphEdge = {"status", "bandwidth","delay","weight","src_as","tgt_as","length","linkType"};
	
    public ParserRIG(File file, File fileOUT) throws IOException {
        this.ftp = file;
		this.fileOut = fileOUT;
        this.fr = new FileReader(this.ftp);
        this.br = new BufferedReader(this.fr);
    }
	
	public void run() {
		try {
			this.parseToXML();
		}
		catch (Exception e) {
			e.printStackTrace();
			Resume result = Resume.getInstance();
			result.add("ParserRIG","procedure run had some problems : "+e);
		}
	}
    
	public void parseToXML() throws IOException {

            // <graphml xmlns="http://graphml.graphdrawing.org/xmlns">
            // <graph edgedefault="undirected">

            Element graphml = new Element("graphml");
            Namespace nsGraphml = Namespace.getNamespace("http://graphml.graphdrawing.org/xmlns");
            graphml.setNamespace(nsGraphml);

            Element graph = new Element("graph");
            Attribute edgedefault = new Attribute("edgedefault", "undirected");
            graph.setAttribute(edgedefault);

		
            Element domain = new Element("domain");
            Element information = new Element("information");
            Element topology = new Element("topology");
            Element igp = new Element("igp");
            Element nodes = new Element("nodes");
            Element links = new Element("links");
            Element igpLinks = new Element("links");
            org.jdom.Document document = new Document(graphml);

		Resume result = Resume.getInstance();
		
		try {
			line = this.br.readLine();
			
			Element title = new Element("title");
			Element date = new Element("date");
			Element author = new Element("author");
			Element description = new Element("description");
			Date today = new Date();
			String day = "";
			String month = "";
			
			title.setText(fileOut.getName());
			if(today.getDate()<10) { day = "0"+today.getDate();} else { day = today.getDate()+""; }
			if((today.getMonth()+1)<10){ month = "0"+(today.getMonth()+1);} else { month = (today.getMonth()+1)+"";}
			date.setText((today.getYear()+1900)+"-"+month+"-"+day);
			author.setText("File Generator");
			description.setText("File generated by ParserRIG from this jApplet");
			
			information.addContent(title);
			information.addContent(date);
			information.addContent(author);
			information.addContent(description);
			
			
			while (line!=null){
				if (line!=null){
					
					if (line.contains("#")){
						if(line.contains("Header")){
							//System.out.println("Case Header");
						}
						if(line.contains("Vertices")){
							//System.out.println("Case Vertices");
							
						}
						if(line.contains("Edges")){
							//System.out.println("Case Edges");
						}
						chaine="";
						//System.out.println(line);
						// it's commentary
					}
					else if(!line.contains(":")){
						res = line.split("\t");
						
						if(res.length<=2){
							// res[0] : number of edges
							// res[1] : number of vertices
						}
						else {
							// res[0] : node id
							// res[1] : latitude
							// res[1] : longitude
							// res[3] : AS-number
							// res[4] : [node name]
							
							
							Element node = new Element("node");
							Attribute id = new Attribute("id",res[0]+"-"+res[3]);
							
							Element AS = Utils.getNameNode("AS", res[3] );
							
							Element location = Utils.getNameNode("location", "" );
                                                        Attribute latitude = new Attribute("latitude",res[1]);
							Attribute longitude = new Attribute("longitude",res[2]);
							
							Element switchNode = Utils.getNameNode("switch", "false" );
                                                        Element statusNode = Utils.getNameNode("status", "UP" );

							node.setAttribute(id);
							location.setAttribute(latitude);
							location.setAttribute(longitude);

                                                        Element NodeName = null;
							if (res.length>=5) {
                                                            NodeName = Utils.getNameNode("name", res[4] );
                                                        }else{
                                                            NodeName = Utils.getNameNode("name", res[0] );
                                                        }

                                                        node.addContent(NodeName);
							
							node.addContent(statusNode);
							node.addContent(AS);
							node.addContent(switchNode);
							node.addContent(location);
							nodes.addContent(node);
							
						}
						
					}
					else if(line.contains(":")){
						// Link case
						res = line.split(":");
						String res2[] = res[1].split("\t");
						String res3[] = res[2].split("\t");
						
						// res[0] : node source AS
						// res2[0] : node id source
						// res2[1] : node target AS
						// res3[0] : node id target
						// res3[1] : type
						// res3[2] : bandwidth
						// res3[3] : weight
						// res3[4] : delay
						// res3[5] : length
						
						Element link = new Element("edge");
						Attribute idLink = new Attribute("id",res2[0]+"-"+res3[0]);
						Attribute srcNode = new Attribute("source",res2[0]+"-"+res[0]);
                                                Attribute tgtNode = new Attribute("target",res3[0]+"-"+res2[1]);

						link.setAttribute(idLink);
                                                link.setAttribute(srcNode);
						link.setAttribute(tgtNode);

						
                                                Element srcAS = Utils.getNameNode("src_as", res[0] );
                                                Element tgtAS = Utils.getNameNode("tgt_as", res2[1] );

						
						Element statusLink = Utils.getNameNode("status", "UP" );
						Element bandwidth = Utils.getNameNode("bandwidth", res3[2] );
                				Element delay = Utils.getNameNode("delay", res3[4] );
						Element weight = Utils.getNameNode("weight", res3[3] );
        					Element length = Utils.getNameNode("length", res3[5] );

						
						Element linkType = Utils.getNameNode("linkType", "" );
						Attribute type2 = new Attribute("type2",res3[1]);
        					linkType.setAttribute(type2);
						
						
						link.addContent(srcAS);
						link.addContent(tgtAS);
						link.addContent(statusLink);
						link.addContent(bandwidth);
						link.addContent(delay);
						link.addContent(linkType);
						link.addContent(length);
						link.addContent(weight);
						
						links.addContent(link);
						
						
					}
					else {}
				}
				line = this.br.readLine();
			}
			br.close();
			fr.close();

                        for (int i = 0; i < keyGraphNode.length; i++) {
                            topology.addContent(Utils.getKeyGraph(i, keyGraphNode, "node"));

                        }

                        for (int i = 0; i < keyGraphEdge.length; i++) {
                            topology.addContent(Utils.getKeyGraph(i, keyGraphEdge, "edge"));

                        }
			
			topology.addContent(nodes);
			topology.addContent(links);
			
			domain.addContent(information);
			domain.addContent(topology);

                        graph.addContent(domain);
                        graphml.addContent(graph);
			
			org.jdom.output.XMLOutputter sortie = new org.jdom.output.XMLOutputter(org.jdom.output.Format.getPrettyFormat());
			sortie.output(document, new FileOutputStream(fileOut.getAbsolutePath()));
			
			result.add("ParserRIG","Import succeeded");
			
		} catch (Exception e) {
			e.printStackTrace();
			result.add("ParserRIG","Import had problems "+e);
		}
	}
}

